<template>
  <div class="app-container">
    <div class="chat-container">
      <!-- 聊天记录区域 -->
      <div>
        <el-card v-if="ready_data.targetUser" class="box-card">
          <div slot="header" class="clearfix">
            正在和 <span style="color: blue;font-weight: bold">{{ ready_data.targetUser.nickname }}</span> 对话中
          </div>
        </el-card>
      </div>
      <el-scrollbar class="chat-messages" ref="scrollbar">
        <div v-for="(msg, index) in messages" :key="index" class="message-item">
          <!-- 客服消息 -->
          <div v-if="!msg.isSelf" class="service-message">
            <el-avatar :src="msg.avatar" class="avatar"></el-avatar>
            <message-itmes :msg="msg"></message-itmes>
          </div>

          <!-- 用户消息 -->
          <div v-else class="user-message">
            <message-itmes :msg="msg"></message-itmes>
            <!--<el-avatar class="avatar" :src="msg.avatar"></el-avatar>-->
          </div>
        </div>
      </el-scrollbar>

      <!-- 输入区域 -->
      <div class="input-area">
        <div class="input-tools">
          <el-popover
            placement="top-start"
            width="300"
            trigger="click"
            class="emoji-picker"
          >
            <div class="emoji-list">
              <span
                v-for="(emoji, index) in emojis"
                :key="index"
                @click="addEmoji(emoji)"
                class="emoji-item"
              >{{ emoji }}</span>
            </div>
            <el-button slot="reference" circle>
              <svg-icon icon-class="biaoqing" class-name="biaoqing"/>
            </el-button>
          </el-popover>

          <!-- 添加选择文件按钮 -->
          <el-button icon="el-icon-picture-outline" title="发送图片" circle @click="triggerFileUpload('image')"
          ></el-button>
          <el-button icon="el-icon-folder-opened" title="发送文件" circle @click="triggerFileUpload('file')"
          ></el-button>
        </div>

        <el-input
          v-model="inputMsg"
          type="textarea"
          :rows="3"
          resize="none"
          @keyup.enter.native="sendMessage"
          class="message-input"
          placeholder="输入消息..."
        ></el-input>

        <el-button
          type="primary"
          @click="sendMessage"
          class="send-btn"
          :disabled="!inputMsg.trim()"
        >发送
        </el-button>
      </div>
    </div>
    <div class="chat-footer">
      <div class="chat-footer-content">
        <div class="chat-footer-left">
          <el-button type="primary" @click="goBack">返回</el-button>
        </div>
      </div>
    </div>

    <!-- 引入 Upload 组件 -->
    <app-upload ref="uploadComponent" @success="handleFileSuccess" :before-upload="beforeMediaUpload" :fields="{to_table:'chat_message'}"></app-upload>
  </div>
</template>

<script>
import api from '@/api/chat'
import MessageItmes from './MessageItmes.vue'
import AppUpload from '@/components/UploadFile/Upload.vue'
import { getToken } from '@/utils/auth' // 引入 Upload 组件

export default {
  components: {
    MessageItmes,
    AppUpload // 注册 Upload 组件
  },
  data() {
    return {
      ready_data: {
        kefu_id: 10000,
        id: 0,
        socketUrl: 'ws://abc.com',
        maxReconnectTimes: 3,
        online: true,
        kefuAvatar: 'https://source.alipay168.cn/skushop/d971248a1565ebf807b6454e6f818916.png',
        targetUser: null
      },
      conversation_id: 0,
      inputMsg: '',
      messages: [],
      emojis: ['😀', '😃', '😄', '😁', '😆', '😅', '🤣', '😍', '🤔', '😴'],
      ws: null,
      reconnectAttempts: 0,
      heartbeatInterval: null, // 新增心跳检测定时器
      leave: false,
      fileType: '',
      currentPage: 1, // 新增当前页码
      pageSize: 30 // 新增每页大小
    }
  },

  mounted() {
    if (this.$route.query.hasOwnProperty('conversation_id')) {
      this.getHistory(this.$route.query.conversation_id)
      api.ready({
        conversation_id: this.$route.query.conversation_id
      }).then(res => {
        console.log(res)
        if (res.code == 0) {
          this.ready_data = res.data
          this.initWebSocket()
        }

      })
    }
  },
  beforeDestroy() {
    this.leave = true
    this.closeWebSocket()
  },
  destroyed() {
    this.leave = true
    this.closeWebSocket()
  },
  methods: {
    initWebSocket() {
      const that = this
      this.ws = new WebSocket(this.ready_data.socketUrl)

      this.ws.onopen = () => {
        console.log('WebSocket connection opened')
        this.reconnectAttempts = 0
        const token = getToken()
        this.ws.send(JSON.stringify({
          type: 'login-kefu',
          token: token,
          kefu_id: this.ready_data.kefu_id,
          targetUser: this.ready_data.targetUser,
          conversation_id: this.conversation_id
        }))
        // 设置心跳检测定时器
        this.heartbeatInterval = setInterval(() => {
          console.log('发送心跳检测')
          that.ws.send(JSON.stringify({ type: 'ping' }))
        }, 30000)
      }

      this.ws.onmessage = (event) => {
        const message = JSON.parse(event.data)
        if (message.type === 'text') {
          this.messages.push({
            isSelf: false,
            avatar: that.ready_data.targetUser.avatar,
            time: new Date().toLocaleTimeString(),
            type: message.type,
            content: message.content
          })
          this.scrollToBottom()
        } else if (message.type === 'file') {
          message.avatar = that.ready_data.targetUser.avatar
          message.isSelf = false
          this.messages.push(message)

        } else if (message.type === 'image') {
          message.avatar = that.ready_data.targetUser.avatar
          message.isSelf = false
          this.messages.push(message)
        } else if (message.type === 'pong') {
          console.log('收到心跳响应')
          return
        } else if (message.type === 'video') {
          message.avatar = that.ready_data.targetUser.avatar
          message.isSelf = false
          this.messages.push(message)
        } else if (message.type === 'error') {
          this.$message({
            type: 'error',
            message: message.content
          })
          return
        }
        this.scrollToBottom()
      }

      this.ws.onclose = () => {
        console.log('WebSocket connection closed')
        if (!this.leave && this.reconnectAttempts < this.ready_data.maxReconnectTimes) {
          setTimeout(() => {
            this.reconnectAttempts++
            this.initWebSocket()
          }, 2000)
        }
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket error:', error)
        this.ws.close()
      }
    },
    closeWebSocket() {
      if (this.ws) {
        this.ws.close()
        this.ws = null
        this.reconnectAttempts = 0
      }
      if (this.heartbeatInterval) {
        clearInterval(this.heartbeatInterval)
        this.heartbeatInterval = null
      }
    },
    loadMoreHistory() { // 新增加载更多历史记录的方法
      this.currentPage++
      this.getHistory(this.$route.query.conversation_id, this.currentPage, this.pageSize)
    },
    getHistory(conversation_id, page = 1, pageSize = 20) { // 修改 getHistory 方法，添加分页参数
      api.history_list({
        conversation_id: conversation_id,
        page: page,
        limit: pageSize
      }).then(res => {
        console.log(res)
        if (res.code === 0) {
          if (page === 1) {
            this.messages = res.data.list
            this.scrollToBottom()
          } else {
            this.messages = [...res.data.list, ...this.messages]
          }

        }
      })
    },

    sendMessage() {
      if (!this.ws) {
        this.$message.error('聊天服务未启动，请联系管理员')
        return
      } else if (this.ws.readyState !== WebSocket.OPEN) {
        this.$message.error('聊天服务未启动，请联系管理员')
        return
      }
      if (!this.inputMsg.trim()) return

      this.messages.push({
        targetUser: this.ready_data.targetUser,
        isSelf: true,
        avatar: this.ready_data.kefuAvatar,
        time: new Date().toLocaleTimeString(),
        type: 'text',
        content: this.inputMsg
      })

      this.ws.send(JSON.stringify({
        type: 'text',
        conversation_id: this.conversation_id,
        avatar: this.ready_data.kefuAvatar,
        content: this.inputMsg
      }))

      this.inputMsg = ''
      this.scrollToBottom()
    },
    addEmoji(emoji) {
      this.inputMsg += emoji
    },
    handleFileSuccess(res, file) {
      const response = res.response
      console.log('uploaded', response)
      if (response.code !== 0) {
        this.$message.error(response.msg)
        return
      }
      const data = response.data
      const type = this.fileType
      this.messages.push({
        isSelf: true,
        avatar: this.ready_data.kefuAvatar,
        time: new Date().toLocaleTimeString(),
        type: type,
        content: data.full_url,
        file_info: {
          name: data.name,
          size: data.size,
          type: data.type,
          url: data.full_url
        }
      })

      this.ws.send(JSON.stringify({
        type: type,
        conversation_id: this.conversation_id,
        avatar: this.ready_data.kefuAvatar,
        content: data.full_url
      }))

      this.scrollToBottom()
    },
    beforeMediaUpload(file) {
      const isMedia = /^image\/(jpeg|png|gif)|^video\/mp4/.test(file.type)
      if (!isMedia) {
        this.$message.error('仅支持上传图片和MP4视频')
        return false
      }
      return true
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const scrollContainer = this.$refs.scrollbar.$el.querySelector('.el-scrollbar__wrap')
        scrollContainer.scrollTop = scrollContainer.scrollHeight

        // 添加滚动事件监听
        scrollContainer.addEventListener('scroll', () => {
          if (scrollContainer.scrollTop === 0) {
            this.loadMoreHistory()
          }
        })
      })
    },
    // 添加触发文件上传的方法
    triggerFileUpload(fileType) {
      if (fileType === 'image') {
        this.fileType = 'image'
      } else if (fileType === 'video') {
        this.fileType = 'video'
      } else {
        this.fileType = 'file'
      }
      this.$refs.uploadComponent.handleClick()
    }
  }
}
</script>

<style scoped>
.app-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #f0f2f5;
  padding: 20px;
}

.chat-container {
  width: 90%;
  max-width: 800px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 90vh;
  margin: 0 auto;

}

/deep/ .el-scrollbar__wrap {
  overflow-x: hidden;
}

.chat-messages {
  flex: 1;
  padding: 10px;
  background: #fafafa;
}

.service-message, .user-message {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.user-message {
  flex-direction: row-reverse;
}

.message-item {
  margin: 15px 0;
  animation: fadeIn 0.3s ease-in-out;
}

.user-message {
  margin-right: 5px;
}

.service-message, .user-message {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.user-message {
  flex-direction: row-reverse;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.input-area {
  padding: 15px;
  border-top: 1px solid #eee;
  background: #fff;
  display: flex;
  gap: 12px;
  align-items: center;
}

.input-tools {
  display: flex;
  gap: 8px;
  margin-bottom: 0;
}

.message-input {
  flex: 1;
  border-radius: 20px !important;
}

.send-btn {
  height: auto;
  padding: 12px 24px;
  border-radius: 20px;
  transition: all 0.2s;
}

.send-btn:hover {
  transform: scale(1.05);
}

.emoji-list {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 6px;
  padding: 8px;
}

.emoji-item {
  cursor: pointer;
  font-size: 20px;
  text-align: center;
  transition: all 0.2s;
}

.emoji-item:hover {
  transform: scale(1.2);
}

.media-wrapper {
  position: relative;
  margin: 4px 0;
}

.video-play-icon {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 40px;
  pointer-events: none;
  opacity: 0.8;
}

.message-link {
  color: #409EFF;
  text-decoration: none;
  word-break: break-all;
}

.message-link:hover {
  text-decoration: underline;
}

@media (max-width: 768px) {
  .chat-container {
    width: 100%;
    height: 100vh;
    border-radius: 0;
    margin: 0;
  }

  .message-content {
    max-width: 85% !important;
  }

  .media-wrapper {
    max-width: 200px !important;
  }
}

.el-button {
  margin-left: unset !important;
}
</style>
